﻿using GameTools.Classes;
using GameTools.Models;
using Loli.Library.Util;
using Loli.Library.WinForm;
using Loli.Library.WinIo;
using PeopleSimulator;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GameTools
{
    public partial class OptionForm : Form
    {
        private Config _Config = null;
        public BindingList<Map> _Maps = null;
        public BindingList<Script> _Scripts = null;
        public BindingList<Player> _Players = null;

        public Config Config
        {
            get
            {
                return this._Config;
            }
            set
            {
                this._Config = value;

                tbHP.Text = Convert.ToString(this.Config.LifeRate);
                tbMP.Text = Convert.ToString(this.Config.MagicRate);
                tbHPCount.Text = Convert.ToString(this.Config.LifePotion);
                tbMPCount.Text = Convert.ToString(this.Config.MagicPotion);
                tbLifeCycleTime.Text = Convert.ToString(this.Config.LifeCycleTime);
                tbMagicCycleTime.Text = Convert.ToString(this.Config.MagicCycleTime);
                tbKeyRate.Text = Convert.ToString(this.Config.KeyRate);
                tbPickCycleTime.Text = Convert.ToString(this.Config.PickCycleTime);
                tbMoveDistance.Text = Convert.ToString(this.Config.MoveDistance);
                tbStepWaitTime.Text = Convert.ToString(this.Config.StepWaitTime);
                cbAlarmPitch.SelectedItem = this.Config.AlarmPitch;
                cbVerificationOffline.Checked = this.Config.IsVerificationOffline;
                tbAlarmInterval.Text = Convert.ToString(this.Config.AlarmInterval);
            }
        }

        public OptionForm()
        {
            DataCenter dc = DataCenter.Load();
            InitializeComponent();

            tbSkillActionTime.Text = "500";
            tbSkillTime.Text = "240";
            tbStepDuration.Text = "1000";


            this.lbSkills.DisplayMember = "DisplayString";
            this.lbSteps.DisplayMember = "DisplayString";

            this._Maps = new BindingList<Map>();
            this.lbMaps.DataSource = _Maps;
            this.lbMaps.DisplayMember = "DisplayString";

            this._Scripts = new BindingList<Script>();
            this.lbScript.DataSource = _Scripts;
            this.lbScript.DisplayMember = "Name";


            this._Players = new BindingList<Player>();
            this.lbPlayers.DataSource = _Players;
            this.lbPlayers.DisplayMember = "Name";


            this.cbSkillType.SelectedIndex = 0;
            this.cbStepConnectionPointMode.SelectedIndex = 0;

            foreach (var item in dc.Maps)
            {
                this._Maps.Add(item);
            }

            /*
            foreach (var item in dc.Scripts)
            {
                this._Scripts.Add(item);
            }*/

            foreach (var item in dc.Players)
            {
                this._Players.Add(item);
            }

            //初始化怪物文件
            //初始化标志文件

            foreach (var item in System.IO.Directory.GetFiles("Datas"))
            {
                string ex = Path.GetExtension(item);
                if (ex.ToLower() == ".mst")
                {
                    this.cbMapMonster.Items.Add(Path.GetFileNameWithoutExtension(item));
                }
                else if (ex.ToLower() == ".ply")
                {
                    this.cbPlayerMark1.Items.Add(Path.GetFileNameWithoutExtension(item));
                }
            }

            cbAlarmPitch.Items.Add(440);
            cbAlarmPitch.Items.Add(446);
            cbAlarmPitch.Items.Add(494);
            cbAlarmPitch.Items.Add(523);
            cbAlarmPitch.Items.Add(554);
            cbAlarmPitch.Items.Add(587);
            cbAlarmPitch.Items.Add(622);
            cbAlarmPitch.Items.Add(659);
            cbAlarmPitch.Items.Add(698);
            cbAlarmPitch.Items.Add(740);
            cbAlarmPitch.Items.Add(784);
            cbAlarmPitch.Items.Add(831);
            cbAlarmPitch.Items.Add(880);
            cbAlarmPitch.Items.Add(988);
            cbAlarmPitch.Items.Add(1047);

        }

        protected override void OnClosing(CancelEventArgs e)
        {
            this.Hide();
            this.InitMapInput();
            this.InitStepInput();
            this.InitPlayerInput();
            this.InitSkillInput();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            //初始化
            this.butApply.Enabled = true;
        }

        private void butScriptCreate_Click(object sender, EventArgs e)
        {
            string name = this.tbScriptName.Text;
            if (string.IsNullOrWhiteSpace(name))
            {
                LoliMessageBox.Show(this, "请填写脚本名称！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            KeyRecordForm KeyRecord = new KeyRecordForm();
            DialogResult result = KeyRecord.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {

                Script script = this._Scripts.FirstOrDefault(t => t.Name == name);
                if (script == null)
                {
                    script = new Script()
                    {
                        CreateTime = DateTime.Now,
                        Name = name,
                        Details = new List<ScriptDetail>()
                    };
                    this._Scripts.Add(script);
                }
                else
                {
                    script.Name = name;
                }
                script.Decscription = tbScriptDescription.Text;
                script.Details.Clear();

                //计算延时
                DateTime now = DateTime.Now;
                for (int i = 0; i < KeyRecord.Details.Count; i++)
                {
                    ScriptDetail detail = KeyRecord.Details[i];
                    if (i != 0)
                    {
                        TimeSpan span = detail.CreateTime - now;
                        script.Details.Add(new ScriptDetail() { Deley = Convert.ToInt32(span.TotalMilliseconds) });
                    }

                    now = detail.CreateTime;
                    script.Details.Add(detail);
                }
                script.Save();

            }
        }

        #region 功能按键
        bool _IsSave = false;

        private void butClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void butSave_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;

            if (!this._IsSave)
            {
                this.Save();
            }

            this.Close();

        }

        private void butApply_Click(object sender, EventArgs e)
        {
            this.Save();
            _IsSave = true;
            this.butApply.Enabled = false;
        }

        private void Save()
        {
            DataCenter dc = DataCenter.Load();
            //获取buff列表             

            this.Config.LifeRate = Convert.ToInt32(tbHP.Text);
            this.Config.MagicRate = Convert.ToInt32(tbMP.Text);
            this.Config.LifePotion = Convert.ToInt32(tbHPCount.Text);
            this.Config.MagicPotion = Convert.ToInt32(tbMPCount.Text);
            this.Config.LifeCycleTime = Convert.ToInt32(tbLifeCycleTime.Text);
            this.Config.MagicCycleTime = Convert.ToInt32(tbMagicCycleTime.Text);
            this.Config.KeyRate = Convert.ToInt32(tbKeyRate.Text);
            this.Config.MoveDistance = Convert.ToInt32(tbMoveDistance.Text);
            this.Config.PickCycleTime = Convert.ToInt32(tbPickCycleTime.Text);
            this.Config.StepWaitTime = Convert.ToInt32(tbStepWaitTime.Text);
            this.Config.AlarmPitch = Convert.ToInt32(cbAlarmPitch.SelectedItem);
            this.Config.IsVerificationOffline = cbVerificationOffline.Checked;
            this.Config.AlarmInterval = Convert.ToInt32(tbAlarmInterval.Text);

            //获取地图列表
            dc.Maps.Clear();
            foreach (var item in this._Maps)
            {
                dc.Maps.Add(item);
            }

            /*
            //获取脚本列表
            dc.Scripts.Clear();
            foreach (var item in this._Scripts)
            {
                dc.Scripts.Add(item);
            }*/

            //获取人物列表
            dc.Players.Clear();
            foreach (var item in this._Players)
            {
                dc.Players.Add(item);
            }

            //保存
            this.Config.Save();
            dc.Maps.Save();
            dc.Players.Save();
            //dc.Scripts.Save();


        }

        #endregion

        #region 人物状态

        private void InitPlayerInput()
        {
            tbPlayerName.Text = string.Empty;
            cbPlayerMark1.SelectedIndex = -1;
            cbPlayerMark2.SelectedIndex = -1;
            cbSkillDirection.SelectedIndex = -1;
            tbSkillRange.Text = "150";

            butPlayerCreate.Text = "添加";
            butPlayerRemove.Text = "移除";
        }

        private void InitSkillInput()
        {
            tbSkillID.Text = string.Empty;
            tbSkillKey.KeyCode = Keys.None;

            butSkillCreate.Text = "添加";
            butSkillRemove.Text = "移除";
        }

        private void lbPlayers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (butPlayerRemove.Text == "取消")
            {
                this.InitPlayerInput();
            }

            Player player = lbPlayers.SelectedItem as Player;
            if (player == null)
            {
                this.lbSkills.DataSource = null;
            }
            else
            {
                this.lbSkills.DisplayMember = "DisplayString";
                this.lbSkills.DataSource = new BindingSource() { DataSource = player.Skills };
            }
        }

        private void lbPlayers_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                int index = lbPlayers.IndexFromPoint(e.X, e.Y);
                if (index >= 0)
                {
                    Player player = lbPlayers.Items[index] as Player;
                    lbPlayers.SelectedIndex = index;

                    tbPlayerName.Text = player.Name;
                    cbPlayerMark1.SelectedItem = player.MarkName1;
                    cbPlayerMark2.SelectedItem = player.MarkName2;
                    cbSkillDirection.SelectedIndex= player.SkillDirection - 1;
                    tbSkillRange.Text = Convert.ToString(player.SkillRange);

                    butPlayerCreate.Text = "修改";
                    butPlayerRemove.Text = "取消";
                }
            }
        }

        private void butPlayerRemove_Click(object sender, EventArgs e)
        {
            if (butPlayerRemove.Text == "取消")
            {
                this.InitPlayerInput();
            }
            else
            {
                if (this.lbPlayers.SelectedItem != null)
                {
                    DialogResult result = LoliMessageBox.Show(this, "确定要删除人物吗？", "信息",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        //_IsChange = true;
                        this._Players.Remove(this.lbPlayers.SelectedItem as Player);
                    }
                }
            }
        }

        private void butPlayerCreate_Click(object sender, EventArgs e)
        {
            string name = tbPlayerName.Text.Trim();
            if (string.IsNullOrEmpty(name))
            {
                LoliMessageBox.Show(this, "请填写角色姓名！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbPlayerName.Focus();
                return;
            }


            string mark1 = Convert.ToString(cbPlayerMark1.SelectedItem);

            if (string.IsNullOrEmpty(mark1))
            {
                LoliMessageBox.Show(this, "请选择人物特征文件！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbPlayerMark1.Focus();
                return;
            }


            string path = string.Format("Datas\\{0}.ply", mark1);
            if (!File.Exists(path))
            {
                LoliMessageBox.Show(this, "人物特征1不存在，请检查目录！", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            string mark2 = Convert.ToString(cbPlayerMark2.SelectedItem);
            path = string.Format("Datas\\{0}.ply", mark2);
            if (!string.IsNullOrEmpty(mark2) && !File.Exists(path))
            {
                LoliMessageBox.Show(this, "人物特征2不存在，请检查目录！", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            int skillDirection = cbSkillDirection.SelectedIndex;
            if (skillDirection == -1)
            {
                LoliMessageBox.Show(this, "请选择人物技能方向！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbSkillDirection.Focus();
                return;
            }

            string skillRange = tbSkillRange.Text;
            if (string.IsNullOrEmpty(skillRange))
            {
                LoliMessageBox.Show(this, "请填写技能影响范围！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbSkillRange.Focus();
                return;
            }

            Player player = null;

            if (butPlayerCreate.Text == "修改")
            {
                player = this._Players.FirstOrDefault(t => t.Name == name);
                if (player == null)
                {
                    DialogResult result = LoliMessageBox.Show(this,
                        string.Format("角色 {0} 不存在，是否创建？", name), "问题", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }

            }
            else
            {
                player = this._Players.FirstOrDefault(t => t.Name == name);
                if (player != null)
                {
                    DialogResult result = LoliMessageBox.Show(this,
                        string.Format("角色 {0} 已经存在，是否覆盖？", name), "问题", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }
            }

            if (player == null)
            {
                player = new Player()
                {
                    Name = name,
                    MarkName1 = Convert.ToString(cbPlayerMark1.SelectedItem),
                    MarkName2 = Convert.ToString(cbPlayerMark2.SelectedItem),
                    SkillDirection = skillDirection + 1,
                    SkillRange = int.Parse(skillRange)
                };
                this._Players.Add(player);
            }
            else
            {
                player.MarkName1 = Convert.ToString(cbPlayerMark1.SelectedItem);
                player.MarkName2 = Convert.ToString(cbPlayerMark2.SelectedItem);
                player.SkillDirection = skillDirection + 1;
                player.SkillRange = int.Parse(skillRange);
            }

            this.InitPlayerInput();
        }

        private void butSkillCreate_Click(object sender, EventArgs e)
        {
            Player player = lbPlayers.SelectedItem as Player;

            if (player == null)
            {
                LoliMessageBox.Show(this, "请先设置人物！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                tbPlayerName.Focus();
                return;
            }

            //获取key
            KeyCodes keyCode = (KeyCodes)tbSkillKey.KeyCode;
            if (keyCode == KeyCodes.None)
            {
                LoliMessageBox.Show(this, "请指定Buff按键！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.tbSkillKey.Focus();
                return;
            }


            int duration = int.Parse(tbSkillTime.Text);
            if (duration <= 0)
            {
                LoliMessageBox.Show(this, "请指定Buff持续时间！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.tbSkillTime.Focus();
                return;
            }


            int actionTime = int.Parse(tbSkillActionTime.Text);
            if (actionTime <= 0)
            {
                LoliMessageBox.Show(this, "请指定Buff独占时间！", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.tbSkillActionTime.Focus();
                return;
            }

            SkillTypes skillType = SkillTypes.Buff;

            if (cbSkillType.SelectedItem.ToString() == "技能")
            {
                skillType = SkillTypes.Attack;
            }

            if (player.Skills == null)
            {
                player.Skills = new List<Skill>();
            };

            int id = player.Skills.Count;
            if (!string.IsNullOrEmpty(tbSkillID.Text))
            {
                id = int.Parse(tbSkillID.Text);
            }

            if (butSkillCreate.Text == "修改")
            {
                Skill skill = player.Skills.FirstOrDefault(t => t.ID == id);
                skill.ActionTime = actionTime;
                skill.Duration = duration;
                skill.KeyCode = keyCode;
                skill.Type = skillType;
            }
            else
            {
                Skill skill = new Skill()
                {
                    ID = id,
                    ActionTime = actionTime,
                    Duration = duration,
                    KeyCode = keyCode,
                    Type = skillType
                };
                player.Skills.Add(skill);
            }

            if (this.lbSkills.DataSource == null)
            {
                this.lbSkills.DisplayMember = "DisplayString";
                this.lbSkills.DataSource = new BindingSource() { DataSource = player.Skills };
            }
            else
            {
                (this.lbSkills.DataSource as BindingSource).ResetBindings(false);
            }

            this.InitSkillInput();
            this.tbSkillKey.Focus();
        }

        private void butSkillRemove_Click(object sender, EventArgs e)
        {
            if (butSkillRemove.Text == "取消")
            {
                this.InitSkillInput();
            }
            else
            {
                Player player = lbPlayers.SelectedItem as Player;
                if (player != null)
                {
                    Skill skill = this.lbSkills.SelectedItem as Skill;
                    if (skill != null)
                    {
                        player.Skills.Remove(this.lbSkills.SelectedItem as Skill);
                        (this.lbSkills.DataSource as BindingSource).ResetBindings(false);

                    }
                }
            }
        }

        private void lbSkills_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                int index = lbSkills.IndexFromPoint(e.X, e.Y);
                if (index >= 0)
                {
                    Skill skill = lbSkills.Items[index] as Skill;
                    lbSkills.SelectedIndex = index;

                    tbSkillID.Text = Convert.ToString(skill.ID);
                    tbSkillKey.KeyCode = (Keys)skill.KeyCode;
                    tbSkillTime.Text = Convert.ToString(skill.Duration);
                    tbSkillActionTime.Text = Convert.ToString(skill.ActionTime);
                    cbSkillType.SelectedItem = skill.Type == SkillTypes.Attack ? "技能" : "状态";

                    butSkillCreate.Text = "修改";
                    butSkillRemove.Text = "取消";
                }
            }
        }

        private void lbSkills_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (butSkillRemove.Text == "取消")
            {
                this.InitSkillInput();
            }
        }

        #endregion

        #region 地图设置

        private void butMapCreate_Click(object sender, EventArgs e)
        {
            string name = tbMapName.Text.Trim();

            if (string.IsNullOrWhiteSpace(name))
            {
                LoliMessageBox.Show(this, "请填写地图名称！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbMapName.Focus();
                return;
            }


            //获取size
            string size = tbMapSize.Text;

            string[] sizes = size.Split('*', '，', ',');
            if (sizes.Length != 2)
            {
                LoliMessageBox.Show(this, "请正确填写地图大小！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbMapSize.Focus();
                return;
            }

            string monster = Convert.ToString(cbMapMonster.SelectedItem);

            if (string.IsNullOrEmpty(monster))
            {
                LoliMessageBox.Show(this, "请选择怪物文件！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbMapMonster.Focus();
                return;
            }

            string path = string.Format("Datas\\{0}.mst", monster);
            if (!File.Exists(path))
            {
                LoliMessageBox.Show(this, "怪物文件不存在，请检查目录！", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            Map map = null;

            if (butMapCreate.Text == "修改")
            {
                map = this._Maps.FirstOrDefault(t => t.Name == name);
                if (map == null)
                {
                    DialogResult result = LoliMessageBox.Show(this,
                        string.Format("地图 {0} 不存在，是否创建？", name), "问题", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }

            }
            else
            {
                map = this._Maps.FirstOrDefault(t => t.Name == name);
                if (map != null)
                {
                    DialogResult result = LoliMessageBox.Show(this,
                        string.Format("地图 {0} 已经存在，是否覆盖？", name), "问题", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }
            }

            if (map == null)
            {
                map = new Map()
                {
                    Name = name,
                    Left = MapleStory._LEFT,
                    Top = MapleStory._TOP,
                    Width = int.Parse(sizes[0]),
                    Height = int.Parse(sizes[1]),
                    MonsterMarkName = monster
                };
                this._Maps.Add(map);
            }
            else
            {
                map.Left = MapleStory._LEFT;
                map.Top = MapleStory._TOP;
                map.Width = int.Parse(sizes[0]);
                map.Height = int.Parse(sizes[1]);
                map.MonsterMarkName = monster;
            }

            this.InitMapInput();
        }

        private void butMapRemove_Click(object sender, EventArgs e)
        {
            if (butMapRemove.Text == "取消")
            {
                this.InitMapInput();
            }
            else
            {
                if (this.lbMaps.SelectedItem != null)
                {
                    DialogResult result = LoliMessageBox.Show(this, "确定要删除地图吗？", "信息",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        this._Maps.Remove(this.lbMaps.SelectedItem as Map);
                    }
                }
            }
        }

        private void lbMaps_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (butMapRemove.Text == "取消")
            {
                this.InitMapInput();
            }
            Map map = lbMaps.SelectedItem as Map;
            if (map == null)
            {
                this.lbSteps.DataSource = null;
            }
            else
            {
                this.lbSkills.DisplayMember = "DisplayString";
                this.lbSteps.DataSource = new BindingSource() { DataSource = map.Steps };
            }
            this.InitStepInput();
        }

        private void lbMaps_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                int index = lbMaps.IndexFromPoint(e.X, e.Y);
                if (index >= 0)
                {
                    Map map = lbMaps.Items[index] as Map;
                    lbMaps.SelectedIndex = index;

                    tbMapSize.Text = map.Width + "*" + map.Height;
                    tbMapName.Text = map.Name;
                    cbMapMonster.SelectedItem = map.MonsterMarkName;

                    butMapRemove.Text = "取消";
                    butMapCreate.Text = "修改";
                }
            }
        }

        private void InitMapInput()
        {
            //清空添加数据         
            this.tbMapName.Text = string.Empty;
            this.tbMapSize.Text = string.Empty;
            this.cbMapMonster.SelectedIndex = -1;
            butMapCreate.Text = "添加";
            butMapRemove.Text = "移除";
        }

        private void butStepCreate_Click(object sender, EventArgs e)
        {
            Map map = lbMaps.SelectedItem as Map;
            if (map == null)
            {
                LoliMessageBox.Show(this, "请先选择地图！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            string left = tbStepLeft.Text.Trim();
            string[] lefts = left.Split('*', '，', ',');
            if (lefts.Length != 2)
            {
                LoliMessageBox.Show(this, "请正确填写左侧坐标！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbStepLeft.Focus();
                return;
            }

            string right = tbStepRight.Text.Trim();

            string[] rights = right.Split('*', '，', ',');
            if (rights.Length != 2)
            {
                LoliMessageBox.Show(this, "请正确填写右侧坐标！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbStepRight.Focus();
                return;
            }

            string connectionPoint = tbStepConnectionPoint.Text.Trim();

            string[] connectionPoints = connectionPoint.Split('*', '，', ',');
            if (connectionPoints.Length != 2)
            {
                LoliMessageBox.Show(this, "请正确填写连接点坐标！", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbStepConnectionPoint.Focus();
                return;
            }

            string duration = tbStepDuration.Text.Trim();
            if (string.IsNullOrEmpty(duration))
            {
                LoliMessageBox.Show(this, "请正确填写动作时间！", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbStepDuration.Focus();
                return;
            }

            if (map.Steps == null)
            {
                map.Steps = new List<Step>();
            }

            int id = map.Steps.Count;
            if (!string.IsNullOrEmpty(tbStepID.Text))
            {
                id = int.Parse(tbStepID.Text);
            }

            int leftX = int.Parse(lefts[0]);
            int leftY = int.Parse(lefts[1]);
            int rightX = int.Parse(rights[0]);
            int rightY = int.Parse(rights[1]);
            int connX = int.Parse(connectionPoints[0]);
            int connY = int.Parse(connectionPoints[1]);
            //验证
            if (leftX >= rightX)
            {
                LoliMessageBox.Show(this, "左侧X坐标必须小于右侧X坐标！", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (leftY != rightY)
            {
                LoliMessageBox.Show(this, "左右两侧Y坐标不同！", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            string modeString = cbStepConnectionPointMode.SelectedItem.ToString();
            Directions mode = Directions.Down;
            switch (modeString)
            {
                case "上":
                    mode = Directions.Up;
                    break;
                case "下":
                    mode = Directions.Down;
                    break;
                case "左":
                    mode = Directions.Left;
                    break;
                case "右":
                    mode = Directions.Right;
                    break;
            }

            Point pleft = new Point(leftX, leftY);
            Point pRight = new Point(rightX, rightY);
            Point pConnectionPoint = new Point(connX, connY);
            int iDuration = int.Parse(duration);
            bool isJump = cbStepJump.Checked;


            if (butStepCreate.Text == "修改")
            {
                Step step = map.Steps.FirstOrDefault(t => t.ID == id);
                step.Left = pleft;
                step.Right = pRight;
                step.ConnectionPoint = pConnectionPoint;
                step.ConnectionPointMode = mode;
                step.Duration = iDuration;
                step.IsJump = isJump;
            }
            else
            {
                Step step = new Step()
                {
                    ID = id,
                    Left = pleft,
                    Right = pRight,
                    ConnectionPoint = pConnectionPoint,
                    ConnectionPointMode = mode,
                    Duration = iDuration,
                    IsJump = isJump
                };
                map.Steps.Add(step);
            }

            if (this.lbSteps.DataSource == null)
            {
                this.lbSteps.DisplayMember = "DisplayString";
                this.lbSteps.DataSource = new BindingSource() { DataSource = map.Steps };
            }
            else
            {
                (this.lbSteps.DataSource as BindingSource).ResetBindings(false);
            }

            this.InitStepInput();

        }

        private void butStepRemove_Click(object sender, EventArgs e)
        {
            if (butStepRemove.Text == "取消")
            {
                this.InitStepInput();
            }
            else if (butStepRemove.Text == "移除")
            {
                Map map = lbMaps.SelectedItem as Map;
                if (map != null)
                {
                    Step step = this.lbSteps.SelectedItem as Step;
                    if (step != null)
                    {
                        map.Steps.Remove(this.lbSteps.SelectedItem as Step);
                        (this.lbSteps.DataSource as BindingSource).ResetBindings(false);
                    }
                }
            }
        }

        private void lbSteps_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                int index = lbSteps.IndexFromPoint(e.X, e.Y);
             
                if (index >= 0)
                {
                    Step step = lbSteps.Items[index] as Step;
                    lbSteps.SelectedIndex = index;

                    cbStepConnectionPointMode.SelectedItem = step.ConnectionPointMode;
                    cbStepJump.Checked = step.IsJump;
                    tbStepRight.Text = step.Right.X + "*" + step.Right.Y;
                    tbStepLeft.Text = step.Left.X + "*" + step.Left.Y;
                    tbStepDuration.Text = step.Duration.ToString();
                    tbStepConnectionPoint.Text = step.ConnectionPoint.X + "*" + step.ConnectionPoint.Y;
                    tbStepID.Text = Convert.ToString(step.ID);

                    butStepCreate.Text = "修改";
                    butStepRemove.Text = "取消";
                }
            }
        }

        private void lbSteps_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (butStepRemove.Text == "取消")
            {
                this.InitStepInput();
            }
        }

        private void InitStepInput()
        {
            tbStepID.Text = string.Empty;
            tbStepDuration.Text = "1000";
            tbStepLeft.Text = string.Empty;
            tbStepRight.Text = string.Empty;
            tbStepConnectionPoint.Text = string.Empty;
            butStepCreate.Text = "添加";
            butStepRemove.Text = "移除";
        }

        private void butGetPoint_Click(object sender, EventArgs e)
        {
            IntPtr handle = MapleStory.FindWindow();

            Map map = lbMaps.SelectedItem as Map;
            if (map == null)
            {
                LoliMessageBox.Show(this, "请先选择地图！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (handle == IntPtr.Zero)
            {
                LoliMessageBox.Show(this, "请先开启游戏！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            WinAPI.ShowWindow(handle, 1);
            WinAPI.SetForegroundWindow(handle);
            Thread.Sleep(500);

            Point point = PlayerAction.FindPlayerLocation(map, DataCenter.Load().Players.Point);
            this.labLocation.Tag = point;
            this.labLocation.Text = point.X + "*" + point.Y;
        }

        private void labLocation_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.msPoint.Show(labLocation, 0, labLocation.Height);
        }

        private void miPointToLeft_Click(object sender, EventArgs e)
        {
            if (this.labLocation.Tag != null)
            {
                Point point = (Point)this.labLocation.Tag;


                ToolStripMenuItem source = sender as ToolStripMenuItem;

                TextBox tb = null;
                switch (source.Name)
                {
                    case "miPointToLeft":
                        tb = tbStepLeft;
                        break;
                    case "miPointToConnection":
                        tb = tbStepConnectionPoint;
                        break;
                    case "miPointToRight":
                        tb = tbStepRight;
                        break;
                }
                tb.Text = point.X + "*" + point.Y;
            }
        }


        #endregion

        #region 基本设置

        private void butSpeak_Click(object sender, EventArgs e)
        {
            DataCenter dc = DataCenter.Load();
            dc._Action.Initialize();

            dc._Action.Speak(Convert.ToInt32(cbAlarmPitch.SelectedItem), 200);
            Thread.Sleep(100);
            dc._Action.Speak(Convert.ToInt32(cbAlarmPitch.SelectedItem), 200);
            Thread.Sleep(100);
            dc._Action.Speak(Convert.ToInt32(cbAlarmPitch.SelectedItem), 200);
            Thread.Sleep(100);
            dc._Action.Speak(Convert.ToInt32(cbAlarmPitch.SelectedItem), 30);
            Thread.Sleep(100);
            dc._Action.Speak(Convert.ToInt32(cbAlarmPitch.SelectedItem), 30);
            Thread.Sleep(100);

            dc._Action.Shutdown();
        }

        #endregion




    }
}
